<?php

namespace App\Http\Controllers;

use App\Http\Models\ContractManager;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Transformers\UserTransformer;
use App\Http\Models\Users;
use App\Http\Models\UserCompany;

class AuthController extends Controller
{

    /**
     * Get a JWT token via given credentials.
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request)
    {
        $user = new Users();
        $res = $user-> getUserapiToken($request->login_id);
        if (sizeof($res) > 0) {
            $params = [
                'api_token' => $res[0]->api_token,
                'password' => $request->password
            ];
            $token = JWTAuth::attempt($params);
            if ($token) {
                $user = new Users();
                $userres = $user -> login($res[0]->api_token);
                if (sizeof($userres) > 0) {
                    $ContractManager = new ContractManager();
                    $resBool = $ContractManager->getContractManager($userres[0]['id']);
                    return $this -> successWithData(['token' => 'bearer ' . $token, 'user' => $userres, 'contractManager' => $resBool]);
                } else {
                    return $this -> tokenErrorWithInfo(config('message.S01LOGIN_LOGINBUTTON_USERDELUSED'));
                }
            } else {
                return $this -> tokenErrorWithInfo(config('message.S01LOGIN_LOGINBUTTON_INVALIDUSERPWD'));
            }
        } else {
            return $this -> tokenErrorWithInfo(config('message.S01LOGIN_LOGINBUTTON_AUTHIDUSERINCORRECT'));
        }
    }

    /**
     * isLogin
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function isLogin(Request $request)
    {
        $user = new Users();
        $userres = $user -> login($request->login);
        if (sizeof($userres) > 0) {
            return $this -> successWithData($userres);
        } else {
            return $this -> tokenErrorWithInfo(config('message.S01LOGIN_LOGINBUTTON_USER'));
        }
    }

    /**
     * authLogin
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function authLogin(Request $request)
    {
        $user = new Users();
        $userres = $user -> login($request->login);
        if (sizeof($userres) > 0) {
            return $this -> successWithData($userres);
        } else {
            return $this -> tokenErrorWithInfo(config('message.S01LOGIN_LOGINBUTTON_USER'));
        }
    }

    /**
     * roleAuth
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleAuth(Request $request)
    {
        $login = $request -> loginId;
        $user = new Users();
        $userres = $user -> login($login);
        if (sizeof($userres) > 0) {
            if ($userres[0] -> Login_User_Role_id === 103 || $userres[0] -> Login_User_Role_id === 101) {
                return  $this -> successWithData(true);
            } else {
                return  $this -> successWithData(false);
            }
        } else {
            return  $this -> successWithData(false);
        }
    }
    public function LoginRoleAuth(Request $request)
    {
        $login = $request -> api_token;
        $user = new Users();
        $userres = $user -> login($login);
        if (sizeof($userres) > 0) {
            return  $this -> successWithData($userres[0]);
        } else {
            return  $this -> successWithData(false);
        }
    }

    /**
     * logout
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function logout()
    {
        Auth::guard('api')->logout();
        return $this -> successWithData(['message' => 'ログアウトしました']);
    }

    /**
     * Refresh a token.
     * トークンの更新：ブラックリストが有効になっている場合、以前のトークンは無効になります。。
     * 上記のgetTokenを使用してトークンを取得することは、リフレッシュとは見なされないことに注意する価値があります。。
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh(Request $request)
    {
//        return $this->respondWithToken(JWTAuth::refresh());

        $token = JWTAuth::refresh(JWTAuth::getToken());
        Log::error("TOKEN");
        Log::error($token);
        JWTAuth::setToken($token);
        $request->user = JWTAuth::authenticate($token);
        $request->headers->set('Authorization','Bearer '.$token);

        return $this -> successWithData(['token' => 'bearer ' . $token]);
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return $this -> successWithData($token);
    }
}
